/**
 * 获取对象距离页面顶部的距离
 */
export function getOffsetTop(el) {
  if (el === document.body || el === document || el === window) return 0;
  return el.offsetTop + (el.offsetParent ? getOffsetTop(el.offsetParent) : 0);
}
/**
 * 获取窗口高度
 */
export function getWinHeight() {
  let clientHeight = 0;
  if (document.body.clientHeight && document.documentElement.clientHeight) {
    clientHeight =
      document.body.clientHeight < document.documentElement.clientHeight
        ? document.body.clientHeight
        : document.documentElement.clientHeight;
  } else {
    clientHeight =
      document.body.clientHeight > document.documentElement.clientHeight
        ? document.body.clientHeight
        : document.documentElement.clientHeight;
  }
  return clientHeight;
}
/**
 * 获取滚动条位置
 */
export function getWinScrollTop() {
  return (
    window.pageYOffset ||
    document.documentElement.scrollTop ||
    document.body.scrollTop
  );
}
/**
 * 移除或添加class名称到指定的元素上
 */
export function addElClass(el, removeClassOrNull, addClassOrNull) {
  let classArr = el.getAttribute("class").split(" ");
  if (removeClassOrNull) {
    classArr = classArr.filter((c) => c.trim() !== removeClassOrNull);
  }
  if (addClassOrNull && !classArr.find((c) => c.trim() === addClassOrNull)) {
    classArr.push(addClassOrNull);
  }
  el.setAttribute("class", classArr.join(" "));
}
/**
 *
 */
export function hasElClass(el, ...classNames) {
  const classArr = el.getAttribute("class").split(" ");
  return !!classArr.find((c) => classNames.includes(c.trim()));
}

export function on(el, events, fn, target, params) {
  events.forEach((ev) => {
    let cb = fn;
    if (target && params) cb = fn.bind(target, params);
    else if (target) cb = fn.bind(target);
    el.addEventListener(ev, cb);
  });
}
/**
 * 移除数组中符合条件的元素(原数组中操作)
 */
export function removeArr(arr, filter) {
  for (let i = 0; i < arr.length; i += 1) {
    if (filter(arr[i])) {
      arr.splice(i, 1);
      i -= 1;
    }
  }
}

export function htmlEncode(str) {
  if (!str || str.length === 0) {
    return "";
  }
  return str
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/ /g, "&nbsp;")
    .replace(/'/g, "&#39;")
    .replace(/"/g, "&quot;");
}
